﻿/*
创建人：zhangrj
日期：2023-11-28
描述：自动开卡规则维护js
*/
var page = {
  pageTotal: 0,
  pageSize: 20,
  pageNumber: 1,
  rootPath: getRootPath(), //网站根路径
  url: getRootPath() + "/Ashx/AutoStartContainerHandler.ashx",
  commonUrl: getRootPath() + "/Ashx/CommonHandler.ashx",
  //初始化页面
  init: function () {
    page.bind();
    page.initPage();
    rulePage.bind();

    imRulePage.bind();
    customizedEasyuiPagination('pp'); //定制化分页
    $("#dgOperaLog").operaLogDialog();//初始化操作日志
    $('.webuploader-pick').css("padding", "3.5px 5px"); //改变上传按钮样式
  },
  //页面事件绑定
  bind: function () {
    //列表加载
    $("#gdContainerStartRuleInfo").datagrid({
      onLoadSuccess: function (data) {
        $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
          total: page.pageTotal,
          pageSize: page.pageSize,
          pageNumber: page.pageNumber
        });
        customizedEasyuiPagination('pp'); //定制化分页
      },
      columns: [[
        { field: 'ck', title: '选择', checkbox: true },
        { field: 'PRODUCTNAME', title: '件号', width: 120 },
        { field: 'PRODUCTREVISION', title: '件号版次', width: 60 },
        { field: 'DESCRIPTION', title: '零件名称', width: 150 },
        { field: 'WORKCENTERNAME', title: '主制工区', width: 100 },
        { field: 'PRODUCTTEAMNAME', title: '件号主制单元', width: 100 },
        { field: 'ISSELFMFGNAME', title: '是否领料', width: 60 },
        { field: 'TECHNOLOGYEMPNAME', title: '工艺员', width: 60 },
        { field: 'CONTAINERTYPENAME', title: '批次类型', width: 80 },
        { field: 'ISCUTCONTAINERNAME', title: '是否切断件', width: 80 },
        { field: 'CUTQTY', title: '分卡数', width: 60 },
        { field: 'CUTSTARTSTEP', title: '分卡工序', width: 80 },
        { field: 'WORKFLOWINFO', title: '工艺规程', width: 180 },
        { field: 'CREATENAME', title: '创建人', width: 60 },
        {
          field: 'CREATEDATE', title: '创建时间', width: 150,
          formatter: function (value, row, index) {
            if (!isNullOrWhiteSpaceStr(value)) {
              return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
            }
          }
        },
        {
          field: 'STATUS', title: '状态', width: 60,
          formatter: function (value, row, index) {
            if (value === 1) {
              return "<span color='blue'>启用</span>";
            } else {
              return "<span color='red'>停用</span>";
            }
          }
        },
        {
          field: 'notes', title: '修改记录', width: 60,
          formatter: function (value, row, index) {
            return '<button class="btnNews" type="button" onclick="page.loadLogData(\'' + row.CONTAINERAUTOSTARTRULEID + '\')">查看</button>'
          }
        }
      ]]
    });

    //查询按钮
    $('#btnSearch').on("click", function () {
      page.pageNumber = 1;
      page.searchData();
    });
    //添加按钮
    $('#btnAdd').on("click", function () {
      page.clearPage(false, false);
      page.openDialog(false);
    });
    //修改按钮
    $('#btnEdit').on("click", function () {
      page.clearPage(false, false);
      page.openDialog(true);
    });
    //启用或停用
    $('#btnChangeStatus').on("click", function () {
      page.clearPage(false, false);
      page.changeStatus();
    });
    //分页事件
    $('#pp').pagination({
      onSelectPage: function (pageNumber, pageSize) {
        customizedEasyuiPagination('pp'); //定制化分页
        page.pageSize = pageSize; page.pageNumber = pageNumber;
        page.searchData();
      }
    });
    //绑定分页go按钮
    $('#pageGo').on("click", function () {
      var pageNumber = $(this).parents('tr').find('.pagination-num').val();
      page.pageNumber = pageNumber;
      page.searchData();
    });
    //清除按钮
    $('#btnReset').on("click", function () {
      page.clearPage(true, true);
      page.pageNumber = 1; page.pageTotal = 0
      $('#pp').pagination('refresh', {
        total: page.pageTotal,
        pageSize: page.pageSize,
        pageNumber: page.pageNumber
      });
    });
  },
  //初始化页面数据
  initPage: function () {
    page.post(page.commonUrl, { action: "getWorkcenterByFactory" }, false, function (res) {
      //主制工区查询
      $('#selWorkCenter').combobox({
        valueField: 'WORKCENTERID',
        textField: 'WORKCENTERNAME',
        data: res,
        onSelect: function (record) {
          if (record.WORKCENTERID) {
            page.getTeam(record.WORKCENTERID);
          }
        }
      });
    });
  },
  //查询
  searchData: function () {
    var params = {
      action: "GetContainerStartRuleData",
      pageSize: page.pageSize,
      pageIndex: page.pageNumber
    };
    var queryFormData = $("#queryForm").serializeArray();
    $.each(queryFormData, function () {
      params[this.name] = this.value;
    });
    page.post(page.url, params, true, function (res) {
      if (!res.Result) {
        displayMessage(res.Message, res.Result);
        return;
      }
      page.pageTotal = res.RowCount;
      $("#gdContainerStartRuleInfo").datagrid('loadData', { total: res.RowCount, rows: res.DBTable });
    });
  },
  // 查询主制单元
  getTeam: function (workcenterid) {
    var mainUrl = getRootPath() + "/Ashx/ProductTeamInfoMaintPageHandler.ashx";//本页面后台路径
    $.ajax({
      type: "post",
      url: mainUrl + "?actions=getTeam",
      data: { action: "getTeam", workcenterid: workcenterid },
      cashe: false,
      dataType: 'json',
      success: function (res) {
        if (res.Result) {
          $("#ddlProductTeam").combobox({
            valueField: 'teamid',
            textField: 'teamname',
            panelHeight: 200,
            data: res.DBTable
          });
        }
      }
    });
  },
  //更改状态
  changeStatus: function () {
    var selectRow = $("#gdContainerStartRuleInfo").datagrid("getChecked");
    if (selectRow.length === 0) {
      displayMessage("请选择数据", false);
      return false;
    }
    var datas = selectRow.map(function (item) {
      return {
        ruleID: item.CONTAINERAUTOSTARTRULEID,
        productName: item.PRODUCTNAME
      }
    });
    var params = {
      ruleType: 1, //状态更改
      datas: JSON.stringify(datas)
    };
    page.post(page.url, { action: "SaveContainerAutoStartRuleData", params: JSON.stringify(params) }, true, function (res) {
      if (res.Result) {
        page.searchData();
      }
      displayMessage(res.Message, res.Result);
    });
  },
  //打开编辑弹窗
  openDialog: function (isEdit) {
    rulePage.ruleID = "";
    if (isEdit) { //编辑
      var selectRow = $("#gdContainerStartRuleInfo").datagrid("getChecked");
      if (selectRow.length === 0) {
        displayMessage("请选择数据", false);
        return false;
      }
      if (selectRow.length > 1) {
        displayMessage("请选择一条数据进行编辑", false);
        return false;
      }
      rulePage.ruleID = selectRow[0].CONTAINERAUTOSTARTRULEID; //记录编辑的数据ID
    }
    page.disableBtn(); //禁用主页面按钮
    $('#dg').dialog({
      onClose: function () {
        page.enableBtn();
      }
    });
    rulePage.init();
  },
  //打开操作日志
  loadLogData: function (ruleID) {
    $("#dgOperaLog").operaLogDialog({ parentID: ruleID, operaType: "AutoStartRule" });
  },
  //禁用页面按钮
  disableBtn: function () {
    $("#mainSec").find(".easyui-linkbutton").each(function () {
      $(this).linkbutton('disable');
    });
  },
  //启用页面按钮
  enableBtn: function () {
    $("#mainSec").find(".easyui-linkbutton").each(function () {
      $(this).linkbutton('enable');
    });
  },
  //清除页面（查询区域，列表区域，填写区域，是否清空消息）
  clearPage: function (query, list) {
    if (query) {
      $("#txtProductName").textbox("clear");
      $("#txtCreateName").textbox("clear", "");
      $("#selWorkCenter").combobox("clear");
      $("#txtTechnologyName").textbox("clear");
      $("#selIsSelfMfg").combobox("clear");
      $("#selIsCutContainer").combobox("clear");
      $("#selStatus").combobox("setValue", "");
      $("#ddlProductTeam").combobox("setValue", "");
    }
    if (list) {
      clearEasyuiDataGrid("gdContainerStartRuleInfo"); //清空列表
    }
  },
  //post数据（路径，参数，是否异步，成功返回方法）
  post: function (url, param, async, callback) {
    $.ajax({
      type: "Post",
      url: url,
      data: param,
      cashe: false,
      async: async,
      dataType: "json",
      beforeSend: function () {
        $.messager.progress({ text: '', msg: '处理中...' });
      },
      success: function (data) {
        $.messager.progress('close');
        callback(data);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        $.messager.progress('close');
        displayMessage(XMLHttpRequest.responseText, false);
        $("body").find(".easyui-linkbutton").each(function () {
          $(this).linkbutton('enable');
        });
      }
    });
  }
};
//规则编辑对象
var rulePage = {
  ruleID: "",
  init: function () {
    rulePage.clearPage();
    rulePage.initPage(); //初始化页面数据
  },
  bind: function () {
    //规则弹窗保存
    $('#btnRuleSave').on("click", function () {
      rulePage.saveData();
    });
    //规则弹窗取消
    $('#btnRuleCancel').on("click", function () {
      $('#dg').dialog("close");
    });
    //件号查询
    $('#btnProductNameSearch').on("click", function () {
      var productName = $("#asInProductName").textbox("getValue");
      if (isNullOrWhiteSpaceStr(productName)) {
        displayMessage("请输入件号", false);
        return;
      }
      var params = {
        action: "GetProductAndWorkFlowInfo",
        productName: productName
      };
      page.post(page.url, params, true, function (res) {
        if (!res.Result) {
          rulePage.clearPage();
          displayMessage(res.Message, res.Result);
          return;
        }
        $("#asCutStartStep").combobox({//分卡工序信息
          valueField: 'WORKFLOWSTEPNAME',
          textField: 'WORKFLOWSTEPNAME',
          panelHeight: 200,
          data: res.DBDataSet.dtStep
        });
        rulePage.bindData(res.DBDataSet.dtProductWorkflow[0], false);
      });
    });
    //件号取消
    $('#btnProductNameCancel').on("click", function () {
      rulePage.clearPage();
    });
    //下拉是否切断件
    $('#asIsCutContainer').combobox({
      onSelect: function (record) {
        if (record.value === "1") {
          $("#cutSection").show();
        } else {
          $("#cutSection").hide();
          $("#asCutQty").numberbox("clear");
          $("#asCutStartStep").combo("clear");
        }
      }
    });
  },
  //初始化页面数据
  initPage: function () {
    page.post(page.url, { action: "InitAutoStartRuleDialogData", ruleID: rulePage.ruleID }, true, function (res) {
      if (!res.Result) {
        displayMessage(res.Message, res.Result);
        return;
      }
      $("#asWorkCenter").combobox({//工区
        valueField: 'WORKCENTERID',
        textField: 'WORKCENTERNAME',
        panelHeight: 200,
        data: res.DBDataSet.dtWorkCenter //下拉数据
      });
      $("#asTechnologyName").combobox({//工艺员
        valueField: 'EMPLOYEEID',
        textField: 'FULLNAME',
        panelHeight: 200,
        data: res.DBDataSet.dtEmployee, //下拉数据
        filter: function (q, row) { //可模糊搜索
          var opts = $(this).combobox('options');
          return row[opts.textField].indexOf(q) > -1;
        }
      });
      //如果是编辑，则绑定数据
      if (rulePage.ruleID !== "") {
        $("#asCutStartStep").combobox({//分卡工序信息
          valueField: 'WORKFLOWSTEPNAME',
          textField: 'WORKFLOWSTEPNAME',
          panelHeight: 200,
          data: res.DBDataSet.dtStep
        });
        rulePage.bindData(res.DBDataSet.dtRule[0], true);
      }
    });
  },
  //绑定数据
  bindData: function (data, isEdit) {
    if (isEdit) { //如果是编辑，则不允许修改件号
      $('#btnProductNameSearch').hide();
      $('#btnProductNameCancel').hide();
    } else {
      $('#btnProductNameSearch').hide();
      $('#btnProductNameCancel').show();
    }
    $("#asInProductName").textbox("setValue", data.PRODUCTNAME);
    $("#asInProductName").textbox({ readonly: true });
    $("#productName").val(data.PRODUCTNAME);
    $("#asProductDesc").val(data.DESCRIPTION);
    $("#asProductRev").val(data.PRODUCTREVISION);
    $("#asWorkflowName").val(data.WORKFLOWNAME);
    $("#asWorkflowRev").val(data.WORKFLOWREVISION);
    if (data.WORKCENTERID != undefined) {
      $("#asWorkCenter").combobox("setValue", data.WORKCENTERID);
    }
    if (data.TECHNOLOGYEMPID != undefined) {
      $("#asTechnologyName").combobox("setValue", data.TECHNOLOGYEMPID);
    }
    if (data.CONTAINERTYPE != undefined) {
      $("#asContainerType").combobox("setValue", data.CONTAINERTYPE);
    }
    if (data.ISSELFMFG != undefined) {
      $("#asIsSelfMfg").combobox("setValue", data.ISSELFMFG);
    }
    if (data.ISCUTCONTAINER != undefined) {
      $("#asIsCutContainer").combobox("setValue", data.ISCUTCONTAINER);
      $("#asCutQty").numberbox("setValue", data.CUTQTY);
      if (!isNullOrWhiteSpaceStr(data.CUTSTARTSTEP)) { //如果分卡工序为空，则表示当前工艺下的工序不存在该分卡工序
        $("#asCutStartStep").combobox("setText", data.CUTSTARTSTEP);
      }
    }
  },
  //保存数据
  saveData: function () {
    var vaild = $('#dgAutoStartForm').form('validate');
    if (vaild === false) {
      displayMessage("请填写必填项", false);
      return;
    }
    var params = {
      ruleID: rulePage.ruleID
    };
    var dgformData = $("#dgAutoStartForm").serializeArray();
    $.each(dgformData, function () {
      params[this.name] = this.value;
    });
    //验证
    if (isNullOrWhiteSpaceStr(params.productName)) {
      displayMessage("未查询件号", false);
      return;
    }
    if (isNullOrWhiteSpaceStr(params.workflowName)) {
      displayMessage("未关联工艺", false);
      return;
    }
    if (isNullOrWhiteSpaceStr(params.workCenterID)) {
      displayMessage("未选择工区", false);
      return;
    }
    if (isNullOrWhiteSpaceStr(params.technologyEmpID)) {
      displayMessage("未选择工艺员", false);
      return;
    }
    if (isNullOrWhiteSpaceStr(params.containerType)) {
      displayMessage("未选择批次类型", false);
      return;
    }
    if (isNullOrWhiteSpaceStr(params.isSelfMfg)) {
      displayMessage("未选择是否领料", false);
      return;
    }
    if (params.isCutContainer === "1") {
      if (isNullOrWhiteSpaceStr(params.cutQty)) {
        displayMessage("未填写分卡数量", false);
        return;
      }
      if (params.cutQty <= 0) {
        displayMessage("分卡数量数值不对，请重新填写", false);
        return;
      }
      if (isNullOrWhiteSpaceStr(params.cutStartStep)) {
        displayMessage("未选择分卡工序", false);
        return;
      }
    }
    params.technologyEmpName = $("#asTechnologyName").combobox("getText");
    params.workCenterName = $("#asWorkCenter").combobox("getText");
    params.containerTypeName = $("#asContainerType").combobox("getText");
    var datas = {
      ruleType: 0, //数据更改
      datas: JSON.stringify(params)
    };
    page.post(page.url, { action: "SaveContainerAutoStartRuleData", params: JSON.stringify(datas) }, true, function (res) {
      if (res.Result) {
        $('#dg').dialog("close");
        page.searchData();
      }
      displayMessage(res.Message, res.Result);
    });
  },
  //清空页面数据
  clearPage: function () {
    $('#btnProductNameSearch').show();
    $('#btnProductNameCancel').hide();
    $("#asInProductName").textbox({ readonly: false });
    $("#asInProductName").textbox("clear");
    $("#productName").val("");
    $("#asProductDesc").val("");
    $("#asProductRev").val("");
    $("#asWorkflowName").val("");
    $("#asWorkflowRev").val("");
    $("#asWorkCenter").combobox("clear");
    $("#asTechnologyName").combobox("clear");
    $("#asContainerType").combobox("clear");
    $("#asIsSelfMfg").combobox("setValue", "1");
    $("#asIsCutContainer").combobox("setValue", "0");
    $("#asCutQty").numberbox("clear");
    $("#asCutStartStep").combo("clear"); //分卡工序全部清空
    $("#asCutStartStep").combo("panel").empty();
  }
};
//规则导入对象
var imRulePage = {
  //绑定事件
  bind: function () {
    $("#ruleImportTable").datagrid({
      columns: [[
        { field: '件号', title: '件号', width: 120 },
        { field: '主制工区', title: '主制工区', width: 100 },
        { field: '是否领料', title: '是否领料', width: 60 },
        { field: '工艺员', title: '工艺员', width: 60 },
        { field: '批次类型', title: '批次类型', width: 80 },
        { field: '是否切断件', title: '是否切断件', width: 80 },
        { field: '分卡数', title: '分卡数', width: 80 },
        { field: '分卡工序', title: '分卡工序', width: 80 },
        {
          field: 'ResultMessage', title: '导入结果', width: 300, formatter: function (value, row, index) {
            if (row.IsResult) {
              return "<span color='blue'>" + value + "</span>";
            } else {
              return "<span color='red'>" + value + "</span>";
            }
          }
        }
      ]]
    });
    //导入模板下载
    $('#btnInportModelDL').on("click", function () {
      window.open(page.rootPath + "/Temp2/导入模板/自动开卡规则维护导入模板.xlsx");
    });
    //导出数据
    $('#btnExportRule').on("click", function () {
      var params = {
        action: "ExportAutoStartRuleToExcel"
      };
      var queryFormData = $("#queryForm").serializeArray();
      $.each(queryFormData, function () {
        params[this.name] = this.value;
      });
      FileDownLoad(page.url, params);
    });
    imRulePage.uploader();
  },
  //导入组件初始化
  uploader: function () {
    var uploaderSeq = WebUploader.create({
      // swf文件路径
      swf: page.rootPath + "/Content/webuploader/Uploader.swf",
      // 文件接收服务端。
      server: page.url,
      // 内部根据当前运行是创建，可能是input元素，也可能是flash.
      pick: '#btnImportRule',
      // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
      resize: false,
      formData: {
        action: "ImportAutoStartRule",
      },
      accept: {
        title: 'Excel',
        extensions: 'xlsx,xls',
        mimeTypes: 'excel/*'
      },
    });
    // 当有文件被添加进队列的时候，每次只传一个文件
    uploaderSeq.on('fileQueued', function (file) {
      clearMessage();
      uploaderSeq.upload();
      $.messager.progress({ text: '', msg: '处理中...' });
    });
    //上传成功
    uploaderSeq.on('uploadSuccess', function (file, response) {
      clearMessage();
      var result = response;
      $.messager.progress('close');
      if (result.Result) {
        imRulePage.loadResultData(result.DBTable);
      }
      displayMessage(result.Message, result.Result);
      var f = uploaderSeq.getFile(file.id); //找到上传的文件
      uploaderSeq.removeFile(f, true); //将其从队列中的删掉

    });
    //上传失败
    uploaderSeq.on('uploadError', function (file) {
      displayMessage("上传失败", false);
      var f = uploaderSeq.getFile(file.id); //找到上传的文件
      uploaderSeq.removeFile(f, true); //将其从队列中的删掉
      $.messager.progress('close');
    });
  },
  //导入结果列表
  loadResultData: function (data) {
    $('#dgRuleImport').dialog({
      title: '导入结果',
      top: 50,
      width: '700px',
      height: '500px',
      closed: false,
      cache: false,
      modal: true,
      buttons: [{
        text: '关闭',
        handler: function () { $('#dgRuleImport').dialog('close'); }
      }]
    });
    $("#ruleImportTable").datagrid('loadData', data);
  }
};
$(function () {
  page.init();
});